package com.Sing.Controller;

import com.Sing.Dao.NoticeMapper;
import com.Sing.Dao.ReaderMapper;
import com.Sing.Pojo.Admin;
import com.Sing.Pojo.Reader;
import com.Sing.Service.AdminServiceImpl;
import com.Sing.Service.ReaderServiceImpl;
import com.Sing.Utils.Constant;
import com.Sing.VerifyCode.IVerifyCodeGen;
import com.Sing.VerifyCode.SimpleCharVerifyCodeGenImpl;
import com.Sing.VerifyCode.VerifyCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;

@Controller
public class LoginController {

    private AdminServiceImpl adminService;
    private ReaderServiceImpl readerService;
    @Autowired
    @Qualifier("adminServiceImpl")
    public void setAdminService(AdminServiceImpl adminService) {
        this.adminService = adminService;
    }
    @Autowired
    @Qualifier("readerServiceImpl")
    public void setReaderService(ReaderServiceImpl readerService) {
        this.readerService = readerService;
    }

    // 生成随机的验证码
    @RequestMapping("/verifyCode")
    public void buildVerify( HttpServletRequest request, HttpServletResponse response ) throws IOException {
        IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();

        try {
            //设置长宽
            VerifyCode verifyCode = iVerifyCodeGen.generate(80, 28);
            String code = verifyCode.getCode();
            //将VerifyCode绑定session
            request.getSession().setAttribute("VerifyCode", code);
            //设置响应头
            response.setHeader("Pragma", "no-cache");
            //设置响应头
            response.setHeader("Cache-Control", "no-cache");
            //在代理服务器端防止缓冲
            response.setDateHeader("Expires", 0);
            //设置响应内容类型
            response.setContentType("image/jpeg");
            response.getOutputStream().write(verifyCode.getImgBytes());
            response.getOutputStream().flush();
        } catch (IOException e) {
            System.out.println("异常处理");
        }
    }

    // 登录函数
    @RequestMapping("/loginIn")
    public String loginIn( String username, String password, String type, HttpServletRequest req, HttpServletResponse resp ){

        if (type == null){
            type = "0";
        }

        // 管理员账户登录
        if ( Integer.parseInt( type ) == 1 ){
            Admin admin = adminService.getDataByCheck(username, password);
            if ( admin != null ){
                System.out.println("管理员登录");
                req.getSession().setAttribute( Constant.USER_SESSION, admin );
                Constant.USER_PASSWORD = password;
                Constant.IS_FIRST = false;

                return "index";
            }

            return "login";
        }

        // 用户账户登录
        if ( Integer.parseInt( type ) == 2 ){
            Reader reader = readerService.getDataByCheck(username, password);
            if ( reader != null ){
                System.out.println("用户登录");
                req.getSession().setAttribute( Constant.USER_SESSION, reader );
                // 让 JSP 页面可以将展示的页面变为对用户展示的页面
                req.getSession().setAttribute( "type", "reader" );
                Constant.USER_PASSWORD = password;
                Constant.IS_FIRST = false;

                return "index";
            }

            return "login";
        }

        return "login";
    }

    //  退出
    @RequestMapping("/loginOut")
    public String loginOut( HttpServletRequest req ){

        req.getSession().removeAttribute( Constant.USER_SESSION );
        Constant.USER_PASSWORD = "";
        Constant.IS_FIRST = true;

        // type 中存在值，还处于 读者登录 的状态
        if ( req.getSession().getAttribute( "type" ) != null ){
            // 删除值，使管理员账户可以正常登录
            req.getSession().removeAttribute( "type" );
        }

        return "login";
    }

    // 跳转页面 ： 密码修改的页面
    @RequestMapping("/updatePassword")
    public String modifyPasswordJump(){

        return "pwdUpdate/updatePwd";
    }

    /**
     * 修改密码
     * @param oldPwd 旧密码 用于验证旧密码是否输入正确
     * @param newPwd 新密码 用于 SQL 的执行
     * @return 返回给 Ajax 进行验证
     */
    @RequestMapping("/updatePwdSubmit2")
    @ResponseBody
    public HashMap<String,Object> modifyPassword(String oldPwd, String newPwd){
        HashMap<String, Object> resultMap = new HashMap<>();

        String userPassword = Constant.USER_PASSWORD;
        if ( oldPwd.equals( userPassword ) ){
            boolean flag = adminService.modifyPWD(newPwd, userPassword);

            Constant.USER_PASSWORD = newPwd;

            resultMap.put( "code", 0 );
            resultMap.put( "msg", "修改成功" );
        }
//        if ( oldPwd.equals( Constant.USER_PASSWORD ) ){
//            boolean flag = adminService.modifyPWD(newPwd, Constant.USER_PASSWORD);
//
//            if ( flag ){
//                resultMap.put( "code", 0 );
//                resultMap.put( "msg", "修改成功" );
//                Constant.USER_PASSWORD = newPwd;
//            }
//        }

        return resultMap;
    }
}
